<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class DevTools extends CI_Controller
{
    private $oldDb = null;

    public function __construct()
    {
        parent::__construct();
        if (defined('ENVIRONMENT') && ENVIRONMENT != 'development') {
            show_404();
        }
        $oldDbConfig['hostname'] = "localhost";
        $oldDbConfig['username'] = "yimeadmin";
        $oldDbConfig['password'] = "yimeadmin";
        $oldDbConfig['database'] = "yimedbadmin";
        $oldDbConfig['dbdriver'] = "mysql";
        $oldDbConfig['dbprefix'] = "y_";
        $oldDbConfig['pconnect'] = FALSE;
        $oldDbConfig['db_debug'] = TRUE;
        $oldDbConfig['cache_on'] = FALSE;
        $oldDbConfig['cachedir'] = "";
        $oldDbConfig['char_set'] = "utf8";
        $oldDbConfig['dbcollat'] = "utf8_general_ci";

        $this->oldDb = $this->load->database($oldDbConfig, true);
    }

    public function migration($ver)
    {
        header("Content-type: text/html; charset=utf-8");
        $this->load->library('migration');
        var_dump($this->migration->version($ver));
        $this->output->enable_profiler(TRUE);
    }

    public function importOldYimeUser()
    {
        header("Content-type: text/html; charset=utf-8");

        ignore_user_abort(true); //忽略客户端连接中断
        set_time_limit(0); //忽略页面执行超时
        ini_set('xdebug.var_display_max_children', 30);

        $this->load->helper('string');
        $this->load->helper('email');
        $this->load->helper('security');

        $this->oldDb->from('userinfo');
        $userinfo = $this->oldDb->get();

        $success_User = array();
        $success_StudentInfo = array();
        $success_UserInfo = array();

        $unSuccess_oldUser = array();
        $unSuccess_oldStudentInfo = array();
        $unSuccess_oldUserInfo = array();

        foreach ($userinfo->result() as $oldUserInfo) {
            $thatUser = new User;
            try {
                //判断邮箱是否合法
                if (!valid_email($oldUserInfo->Uemail)) {
                    throw new FormatException('不是合法的邮箱地址');
                }
                //判断邮箱是否已被使用
                if (UserManager::isEmailExist($oldUserInfo->Uemail)) {
                    throw new AlreadyExistException('邮箱已被使用');
                }

                $thatUser->setEmail($oldUserInfo->Uemail);

                if ($oldUserInfo->Ualais)
                    $thatUser->setNickname($oldUserInfo->Ualais);

                //单纯MD5散列的密码
                $thatUser->setSalt('#MD5#');
                $thatUser->setPassword($oldUserInfo->Upasswd);

                if ($oldUserInfo->Upower >= 1) {
                    //已通过邮箱认证
                    $thatUser->setPower(1);
                }

                if ($oldUserInfo->LoginIP)
                    $thatUser->setRegIp($oldUserInfo->LoginIP);
                else
                    $thatUser->setRegIp('127.0.0.1');
                $thatUser->setRegTime(date("Y-m-d H:i:s", $oldUserInfo->Uregtime));

                $thatUser = User_Model::add($thatUser);

                $success_User[] = $thatUser;

                //实名认证信息
                if (!$thatUser->getStudentInfoId() && $oldUserInfo->Upower >= 2) {
                    try {
                        $thatStudentInfo = new StudentInfo;

                        //检查数据可用性
                        if (!$oldUserInfo->USid) throw new Exception('学号为空');
                        if (!$oldUserInfo->Uname) throw new Exception('姓名为空');
                        if (!$oldUserInfo->Ugrade) throw new Exception('年级为空');
                        if (!$oldUserInfo->Umajor) throw new Exception('专业为空');
                        if (StudentInfo_Model::isSchoolIdAndStudentNumExist($oldUserInfo->Sid, $oldUserInfo->USid)) throw new Exception('学号已被使用');

                        $thatStudentInfo->setStudentNum($oldUserInfo->USid);
                        $thatStudentInfo->setStudentName($oldUserInfo->Uname);
                        $thatStudentInfo->setGrade($oldUserInfo->Ugrade);
                        $thatStudentInfo->setMajor($oldUserInfo->Umajor);
                        $thatStudentInfo->setUserId($thatUser->getId());
                        $thatStudentInfo->setSchoolId($oldUserInfo->Sid);

                        $thatStudentInfo = StudentInfo_Model::add($thatStudentInfo);

                        $success_StudentInfo[] = $thatStudentInfo;

                        $thatUser->setStudentInfoId($thatStudentInfo->getId());
                        $thatUser = User_Model::update($thatUser);
                    } catch (Exception $ex) {
                        $unSuccess_oldStudentInfo[] = array($oldUserInfo, $ex->getMessage());
                    }
                }

                //用户扩展信息
                if (!$thatUser->getUserInfoId()) {
                    try {
                        $thatUserInfo = new UserInfo();

                        if ($oldUserInfo->Uname) $thatUserInfo->setRealName($oldUserInfo->Uname);
                        if ($oldUserInfo->Usex == '男') $thatUserInfo->setSex(1);
                        else if ($oldUserInfo->Usex == '女') $thatUserInfo->setSex(2);

                        if ($oldUserInfo->Ucity) {
                            $array = explode(' ', $oldUserInfo->Ucity);
                            if (isset($array[0]) && $array[0]) $thatUserInfo->setProv($array[0]);
                            if (isset($array[1]) && $array[1]) $thatUserInfo->setCity($array[1]);
                            if (isset($array[2]) && $array[2]) $thatUserInfo->setDist($array[2]);
                        }

                        if ($oldUserInfo->Ucontact) {
                            if ($oldUserInfo->Ucontact_type == 'QQ') {
                                $thatUserInfo->setQq($oldUserInfo->Ucontact);
                            } else if ($oldUserInfo->Ucontact_type == '短号') {
                                $thatUserInfo->setPhoneShort($oldUserInfo->Ucontact);
                            } else if ($oldUserInfo->Ucontact_type == '长号') {
                                $thatUserInfo->setPhone($oldUserInfo->Ucontact);
                            } else if ($oldUserInfo->Ucontact_type == '联系电话') {
                                $thatUserInfo->setPhone($oldUserInfo->Ucontact);
                            }
                        }

                        if ($oldUserInfo->Umyword) {
                            $thatUserInfo->setProfile($oldUserInfo->Umyword);
                        }

                        if ($oldUserInfo->Uimage_big) {
                            $thatUserInfo->setAvatarHash('#OLD_PATH#' . $oldUserInfo->Uimage_big);
                        }

                        $thatUserInfo->setUserId($thatUser->getId());

                        $thatUserInfo = UserInfo_Model::add($thatUserInfo);

                        $success_UserInfo[] = $thatUserInfo;

                        $thatUser->setUserInfoId($thatUserInfo->getId());
                        $thatUser = User_Model::update($thatUser);
                    } catch (Exception $ex) {
                        $unSuccess_oldUserInfo[] = array($oldUserInfo, $ex->getMessage());
                    }
                }
            } catch (Exception $ex) {
                $unSuccess_oldUser[] = array($oldUserInfo, $ex->getMessage());
            }
        }

        echo '<p>导入成功 ' . sizeof($success_User) . ' 个用户</p>';
        echo '<p>导入成功 ' . sizeof($success_StudentInfo) . ' 个实名用户</p>';
        echo '<p>导入成功 ' . sizeof($success_UserInfo) . ' 个用户扩展信息</p>';
        echo '<p>导入失败 ' . sizeof($unSuccess_oldUser) . ' 个用户</p>';
        echo '<p>导入失败 ' . sizeof($unSuccess_oldStudentInfo) . ' 个实名用户</p>';
        echo '<p>导入失败 ' . sizeof($unSuccess_oldUserInfo) . ' 个用户扩展信息</p>';

        $this->output->enable_profiler(TRUE);
    }

    public function importOldYimeCommodity()
    {
        header("Content-type: text/html; charset=utf-8");

        ignore_user_abort(true); //忽略客户端连接中断
        set_time_limit(0); //忽略页面执行超时
        ini_set('xdebug.var_display_max_children', 30);

        $this->oldDb->from('message');
        $message = $this->oldDb->get()->result();

        $success_Commodity = array();
        $unSuccess_oldCommodity = array();

        foreach ($message as $oldCommodity) {
            try {
                if (!$oldCommodity->id) throw new Exception('用户ID为空');
                if (!$oldUserInfo = $this->oldDb->from('userinfo')->where('id', $oldCommodity->id)->get()->row()) throw new Exception('找不到相对应的用户');
                if (!$email = $oldUserInfo->Uemail) throw new Exception('找不到对应的Email地址');
                if (!$user = User_Model::getUserByEmail($email)) throw new Exception('找不到该Email地址对应的用户');
                $commodity = new Commodity();
                $commodity->setUserId(intval($user->getId()));

                if (!$oldCommodity->Mtitle) throw new Exception('商品标题不存在');
                $commodity->setTitle($oldCommodity->Mtitle);
                $commodity->setIntro($oldCommodity->Msmallcontent);
                $commodity->setContent('#OLD_CONTENT#' . $oldCommodity->Mcontent);
                $commodity->setPrice(doubleval($oldCommodity->Mprice));
                $commodity->setStock(intval($oldCommodity->Mnum));

                if ($oldCommodity->Mstate == '全新')
                    $commodity->setReleaseType(1);
                if ($oldCommodity->Mstate == '二手')
                    $commodity->setReleaseType(2);
                if ($oldCommodity->Mstate == '赠送')
                    $commodity->setReleaseType(3);

                $commodity->setReleaseTime(date("Y-m-d H:i:s", $oldCommodity->Mdatetime));

                $preg_match_result = array();
                if (preg_match('/^(?:长号|联系电话|手机)(?::|：|\.|\s)?(\d+)(?:.*)$/', $oldCommodity->Mlianxi, $preg_match_result)) {
                    if (isset($preg_match_result[1]) && $preg_match_result[1]) {
                        $commodity->setContactType(_ContactType_LongPhone);
                        $commodity->setContactInfo($preg_match_result[1]);
                    }
                } else if (preg_match('/^(?:短号)(?::|：|\.|\s)?(\d+)(?:.*)$/', $oldCommodity->Mlianxi, $preg_match_result)) {
                    if (isset($preg_match_result[1]) && $preg_match_result[1]) {
                        $commodity->setContactType(_ContactType_ShortPhone);
                        $commodity->setContactInfo($preg_match_result[1]);
                    }
                } else if (preg_match('/^(?:加)?(?:QQ|qq|Q|扣扣)(?::|：|\.|\s)?(\d+)(?:.*)$/', $oldCommodity->Mlianxi, $preg_match_result)) {
                    if (isset($preg_match_result[1]) && $preg_match_result[1]) {
                        $commodity->setContactType(_ContactType_Qq);
                        $commodity->setContactInfo($preg_match_result[1]);
                    }
                } else if (preg_match('/^(?:微信(?:ID|号|“)?)(?::|：|\.|\s)?(\S+)(?:.*)$/', $oldCommodity->Mlianxi, $preg_match_result)) {
                    if (isset($preg_match_result[1]) && $preg_match_result[1]) {
                        $commodity->setContactType(_ContactType_WeiXin);
                        $commodity->setContactInfo($preg_match_result[1]);
                    }
                } else if (preg_match('/^(\d{11}(?:.*))$/', $oldCommodity->Mlianxi, $preg_match_result)) {
                    if (isset($preg_match_result[1]) && $preg_match_result[1]) {
                        $commodity->setContactType(_ContactType_LongPhone);
                        $commodity->setContactInfo($preg_match_result[1]);
                    }
                } else if (preg_match('/^(\d{6})$/', $oldCommodity->Mlianxi, $preg_match_result)) {
                    if (isset($preg_match_result[1]) && $preg_match_result[1]) {
                        $commodity->setContactType(_ContactType_ShortPhone);
                        $commodity->setContactInfo($preg_match_result[1]);
                    }
                } else if (preg_match('/^(\d{9})$/', $oldCommodity->Mlianxi, $preg_match_result)) {
                    if (isset($preg_match_result[1]) && $preg_match_result[1]) {
                        $commodity->setContactType(_ContactType_Qq);
                        $commodity->setContactInfo($preg_match_result[1]);
                    }
                } else {
                    $commodity->setContactType(_ContactType_None);
                    $commodity->setContactInfo($oldCommodity->Mlianxi);
                }

                switch ($oldCommodity->Mclassify) {
                    case '电脑周边':
                        $commodity->setCommodityCatId(4);
                        break;
                    case '手机通讯':
                        $commodity->setCommodityCatId(2);
                        break;
                    case '数码产品':
                        $commodity->setCommodityCatId(1);
                        break;
                    case '服装时尚':
                        $commodity->setCommodityCatId(21);
                        break;
                    case '生活用品':
                        $commodity->setCommodityCatId(9);
                        break;
                    case '书籍文具':
                        $commodity->setCommodityCatId(14);
                        break;
                    case '交通工具':
                        $commodity->setCommodityCatId(26);
                        break;
                    case '工艺饰品':
                        $commodity->setCommodityCatId(17);
                        break;
                    case '其他':
                        $commodity->setCommodityCatId(26);
                        break;
                    default:
                        $commodity->setCommodityCatId(26);
                        break;
                }

                if ($oldCommodity->Mimage1) {
                    $commodity->setImageHash('#OLD_PATH#' . $oldCommodity->Mimage1);
                }

                $commodity->setSchoolunicode(12618);

                $commodity = Commodity_Model::add($commodity);

                $success_Commodity[] = $commodity;
            } catch (Exception $ex) {
                $unSuccess_oldCommodity[] = array($oldCommodity, $ex->getMessage());
            }
        }

        echo '<p>导入成功 ' . sizeof($success_Commodity) . ' 个Commodity </p>';
        echo '<p>导入失败 ' . sizeof($unSuccess_oldCommodity) . ' 个Commodity</p>';

        $this->output->enable_profiler(TRUE);
    }

    public function importOldYimeCommodityRequire()
    {
        header("Content-type: text/html; charset=utf-8");

        ignore_user_abort(true); //忽略客户端连接中断
        set_time_limit(0); //忽略页面执行超时
        ini_set('xdebug.var_display_max_children', 30);

        $this->oldDb->from('require');
        $require = $this->oldDb->get()->result();

        $success_CommodityRequire = array();
        $unSuccess_oldCommodityRequire = array();

        foreach ($require as $oldCommodityRequire) {
            try {
                if (!$oldCommodityRequire->id) throw new Exception('用户ID为空');
                if (!$oldUserInfo = $this->oldDb->from('userinfo')->where('id', $oldCommodityRequire->id)->get()->row()) throw new Exception('找不到相对应的用户');
                if (!$email = $oldUserInfo->Uemail) throw new Exception('找不到对应的Email地址');
                if (!$user = User_Model::getUserByEmail($email)) throw new Exception('找不到该Email地址对应的用户');
                $commodityRequire = new CommodityRequire();
                $commodityRequire->setUserId(intval($user->getId()));

                if (!$oldCommodityRequire->Qtitle) throw new Exception('商品标题不存在');
                $commodityRequire->setTitle($oldCommodityRequire->Qtitle);
                $commodityRequire->setContent($oldCommodityRequire->Qcontent);

                $commodityRequire->setNum(null);
                $commodityRequire->setReleaseType(0);
                $commodityRequire->setReleaseTime(date("Y-m-d H:i:s", $oldCommodityRequire->Qtime));

                switch ($oldCommodityRequire->Qcontact_type) {
                    case '短号':
                        $commodityRequire->setContactType(_ContactType_ShortPhone);
                        $commodityRequire->setContactInfo($oldCommodityRequire->Qcontact);
                        break;
                    case '长号':
                        $commodityRequire->setContactType(_ContactType_LongPhone);
                        $commodityRequire->setContactInfo($oldCommodityRequire->Qcontact);
                        break;
                    case 'QQ':
                        $commodityRequire->setContactType(_ContactType_Qq);
                        $commodityRequire->setContactInfo($oldCommodityRequire->Qcontact);
                        break;
                    case "联系电话":
                        if (strlen($oldCommodityRequire->Qcontact) == 11)
                            $commodityRequire->setContactType(_ContactType_LongPhone);
                        else
                            $commodityRequire->setContactType(_ContactType_ShortPhone);
                        $commodityRequire->setContactInfo($oldCommodityRequire->Qcontact);
                        break;
                    default:
                        $commodityRequire->setContactType(_ContactType_None);
                        $commodityRequire->setContactInfo($oldCommodityRequire->Qcontact);
                        break;
                }

                $commodityRequire->setSchoolunicode(12618);

                $preg_match_result = array();
                if (preg_match('/^留言我$/', $oldCommodityRequire->Qprice, $preg_match_result)) {
                    $commodityRequire->setMinPrice(0);
                    $commodityRequire->setMaxPrice(0);
                } else if (preg_match('/^(\d+)(?:元)?\-(\d+)(?:元)$/', $oldCommodityRequire->Qprice, $preg_match_result)) {
                    if (isset($preg_match_result[1]) && isset($preg_match_result[2])) {
                        $commodityRequire->setMinPrice(doubleval($preg_match_result[1]));
                        $commodityRequire->setMaxPrice(doubleval($preg_match_result[2]));
                    }
                } else {
                    $commodityRequire->setMinPrice(0);
                    $commodityRequire->setMaxPrice(0);
                }

                $commodityRequire = CommodityRequire_Model::add($commodityRequire);

                $success_CommodityRequire[] = $commodityRequire;
            } catch (Exception $ex) {
                $unSuccess_oldCommodityRequire[] = array($oldCommodityRequire, $ex->getMessage());
            }
        }

        echo '<p>导入成功 ' . sizeof($success_CommodityRequire) . ' 个CommodityRequire </p>';
        echo '<p>导入失败 ' . sizeof($unSuccess_oldCommodityRequire) . ' 个CommodityRequire </p>';

        $this->output->enable_profiler(TRUE);
    }


    public function importOldYimeComment()
    {
        header("Content-type: text/html; charset=utf-8");

        ignore_user_abort(true); //忽略客户端连接中断
        set_time_limit(0); //忽略页面执行超时
        ini_set('xdebug.var_display_max_children', 30);

        $this->oldDb->from('messagereply');
        $messagereply = $this->oldDb->get()->result();

        $success_Comment = array();
        $success_RequireComment = array();
        $unSuccess_oldComment = array();

        foreach ($messagereply as $oldComment) {
            try {
                if (!$oldComment->Uid) throw new Exception('用户ID为空');
                if (!$oldUserInfo = $this->oldDb->from('userinfo')->where('id', $oldComment->Uid)->get()->row()) throw new Exception('找不到相对应的用户');
                if (!$email = $oldUserInfo->Uemail) throw new Exception('找不到对应的Email地址');
                if (!$user = User_Model::getUserByEmail($email)) throw new Exception('找不到该Email地址对应的用户');

                if ($oldComment->Mid && !$oldComment->Qid) {
                    $commodityComment = new CommodityComment();
                    $commodityComment->setUserId(intval($user->getId()));

                    if (!$oldComment->Rcontent) throw new Exception('评论内容不存在');
                    $commodityComment->setContent($oldComment->Rcontent);
                    $commodityComment->setPrivate($oldComment->Rcollogue);
                    $commodityComment->setReleaseTime(date("Y-m-d H:i:s", $oldComment->Rdatetime));

                    if (!$oldCommodity = $this->oldDb->from('message')->where('Mid', $oldComment->Mid)->get()->row()) throw new Exception('找不到相对应的商品');
                    if (!$commodity = Commodity_Model::getCommodityByTitle($oldCommodity->Mtitle)) throw new Exception('在新版商品中找不到对应的标题');
                    $commodityComment->setCommodityId($commodity->getId());

                    if ($oldComment->Rpid != 0) {
                        $father = null;
                        foreach ($messagereply as $t) {
                            if ($t->Rid == $oldComment->Rpid) {
                                $father = $t;
                                break;
                            }
                        }
                        if (!$father) throw new Exception('找不到父级留言');

                        foreach ($success_Comment as $comment) {
                            /** @var CommodityComment $comment */
                            if ($comment->getReleaseTime() == date("Y-m-d H:i:s", $father->Rdatetime)){
                                $commodityComment->setFatherId($comment->getId());
                            }
                        }
                        if (!$commodityComment->getFatherId()) throw new Exception('在新版留言中找不到对应的父级留言');
                    }

                    $commodityComment = CommodityComment_Model::add($commodityComment);

                    $success_Comment[] = $commodityComment;
                } else if (!$oldComment->Mid && $oldComment->Qid) {

                    $commodityRequireComment = new CommodityRequireComment();
                    $commodityRequireComment->setUserId(intval($user->getId()));

                    if (!$oldComment->Rcontent) throw new Exception('评论内容不存在');
                    $commodityRequireComment->setContent($oldComment->Rcontent);
                    $commodityRequireComment->setPrivate($oldComment->Rcollogue);
                    $commodityRequireComment->setReleaseTime(date("Y-m-d H:i:s", $oldComment->Rdatetime));

                    if (!$oldCommodity = $this->oldDb->from('require')->where('Qid', $oldComment->Qid)->get()->row()) throw new Exception('找不到相对应的求购');
                    if (!$commodityRequire = CommodityRequire_Model::getCommodityRequireByTitle($oldCommodity->Qtitle)) throw new Exception('在新版求购中找不到对应的标题');
                    $commodityRequireComment->setCommodityRequireId($commodityRequire->getId());

                    if ($oldComment->Rpid != 0) {
                        $father = null;
                        foreach ($messagereply as $t) {
                            if ($t->Rid == $oldComment->Rpid) {
                                $father = $t;
                                break;
                            }
                        }
                        if (!$father) throw new Exception('找不到父级留言');

                        foreach ($success_RequireComment as $comment) {
                            /** @var CommodityComment $comment */
                            if ($comment->getReleaseTime() == date("Y-m-d H:i:s", $father->Rdatetime)){
                                $commodityRequireComment->setFatherId($comment->getId());
                            }
                        }
                        if (!$commodityRequireComment->getFatherId()) throw new Exception('在新版留言中找不到对应的父级留言');
                    }

                    $commodityRequireComment = CommodityRequireComment_Model::add($commodityRequireComment);

                    $success_RequireComment[] = $commodityRequireComment;
                }
            } catch (Exception $ex) {
                $unSuccess_oldComment[] = array($oldComment, $ex->getMessage());
            }
        }

        echo '<p>导入成功 ' . sizeof($success_Comment) . ' 个CommodityComment </p>';
        echo '<p>导入成功 ' . sizeof($success_RequireComment) . ' 个CommodityRequireComment </p>';
        echo '<p>导入失败 ' . sizeof($unSuccess_oldComment) . ' 个 </p>';

        var_dump($unSuccess_oldComment);

        $this->output->enable_profiler(TRUE);
    }

    public function importOldPower()
    {

    }
}